package com.mxl.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    /**
     * 验证用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Object login(String username, String password) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            return "用户名不存在!";
        } catch (IncorrectCredentialsException ice) {
            return "密码不正确!";
        } catch (LockedAccountException lae) {
            return "账户已锁定!";
        } catch (ExcessiveAttemptsException eae) {
            return "用户名或密码错误次数过多!";
        } catch (AuthenticationException ae) {
            return "用户名或密码不正确！";
        }
        if (subject.isAuthenticated()) {
            return "登录成功!";
        } else {
            token.clear();
            return "登录失败!";
        }
    }


    @RequestMapping(value = "/notLogin")
    public Object notLogin() {
        return "您尚未登陆！";
    }

    @RequestMapping(value = "/notRole")
    public Object notRole() {
        return "您没有权限！";
    }

    @RequestMapping(value = "/logout")
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        //注销
        subject.logout();
        return "成功注销！";
    }
}
